<template>
  <q-dialog seamless v-model="visible" position="top">
    <div class="q-pa-sm blur">
      <div class="flex justify-center q-gutter-sm">
        <q-btn
          class="text-bold"
          label="结束定位"
          color="secondary"
          icon-right="location_off"
          @click="close"
        />
        <q-btn
          class="text-bold"
          :label="isLocation ? '当前模式：修改位置' : '当前模式：修改方向'"
          color="secondary"
          :icon-right="isLocation ? 'replay' : 'shuffle'"
          @click="changeMode()"
        />
      </div>
    </div>
  </q-dialog>
</template>

<script setup>
import { ref, inject, watch } from "vue";
import { useQuasar } from "quasar";
import { useUiStore } from "stores/ui";

const $q = useQuasar();
const ui = useUiStore();
const visible = ref(false);
const pixiMap = inject("pixiMap");
const pointList = ref([]);
const newList = ref([]);
const point = ref({});
const isLocation = ref(true);
const emit = defineEmits(["relocateSave"]);

defineExpose({ show });
// 修改模式
function changeMode() {
  isLocation.value = !isLocation.value;
}
function show(data, list) {
  pixiMap.poseState = true;
  newList.value = list;
  pointList.value = JSON.parse(JSON.stringify(newList.value));
  pointList.value.forEach((item, index) => {
    if (item.id === data.id) {
      point.value = pointList.value[index];
    }
  });
  visible.value = true;
  // 重定位和方向修改
  pixiMap.clickPose = (e) => {
    const pos = pixiMap.globalToRos(e.data.global.x, e.data.global.y);
    if (isLocation.value) {
      point.value.pose.position.x = pos.x;
      point.value.pose.position.y = pos.y;
    } else {
      const theta = Math.atan2(
        pos.y - point.value.pose.position.y,
        pos.x - point.value.pose.position.x
      );
      point.value.pose.orientation.z = Math.sin(theta / 2);
      point.value.pose.orientation.w = Math.cos(theta / 2);
    }
    pointList.value.forEach((item, index) => {
      if (item.id === point.value.id) {
        pointList.value[index] = point.value;
      }
    });
    pixiMap.drawRail(pointList.value);
  };
}
// 监听组件关闭后吧定位关闭
watch(visible, (value) => {
  if (!value) {
    pixiMap.poseState = false;
  }
});
function close() {
  // 判断是否修改
  if (JSON.stringify(pointList.value) === JSON.stringify(newList.value)) {
    visible.value = false;
  } else {
    $q.dialog({
      dark: ui.isDark,
      title: "提示",
      message: "是否保存当前重定位信息 ？",
      ok: "保存",
      cancel: "不保存",
    })
      .onOk(() => {
        emit("relocateSave", pointList.value);
        visible.value = false;
      })
      .onCancel(() => {
        pixiMap.drawRail(newList.value);
        visible.value = false;
      });
  }
}
</script>

<style scoped></style>
